package com.falcon.system.listener;

import com.alibaba.fastjson.JSONObject;
import com.falcon.system.domain.po.SystemLogPO;
import com.falcon.system.mapper.ISystemLogMapper;
import com.swan.test.constant.LogConstant;
import com.swan.test.listener.ILogEventListener;
import com.swan.test.listener.LogInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/** 自定义日志监听器: 自定义接入时，要记得异步处理
 * @author zongf
 * @date 2024-02-04
 **/
@Component
public class LogbackMysqlAppender implements ILogEventListener {

    @Autowired
    private ISystemLogMapper systemLogMapper;

    @Override
    public void handle(LogInfo logInfo) {
        if (logInfo == null) {
            return;
        }

        // 排除 ISystemLogMapper 打印的日志，否则进入无限循环了
        if (logInfo.getLogger().contains("ISystemLogMapper")) {
            return;
        }

        SystemLogPO systemLogPO = new SystemLogPO();
        systemLogPO.setLogTime(new Date(logInfo.getLogTime()));
        systemLogPO.setLogger(logInfo.getLogger());
        systemLogPO.setThreadName(logInfo.getThreadName());
        systemLogPO.setLevel(logInfo.getLevel());
        systemLogPO.setMessage(logInfo.getMessage());
        systemLogPO.setThrowableStack(logInfo.getThrowableStack());
        systemLogPO.setClassName(logInfo.getClassName());
        systemLogPO.setMethodName(logInfo.getMethodName());
        systemLogPO.setLineNumber(logInfo.getLineNumber());

        if (Objects.nonNull(logInfo.getMdcProperty())) {
            systemLogPO.setMdc(JSONObject.toJSONString(logInfo.getMdcProperty().toString()));
            systemLogPO.setLogId(logInfo.getMdcProperty().get(LogConstant.LOG_ID));
        }

        this.systemLogMapper.insertNotNull(systemLogPO);
    }
}
